extends Control

@export var choose_box_width : int = 2
@export var drag_distance_min_limit : int = 20

@onready var box : Panel = get_node("Box")
@onready var mousePos : Vector2 = Vector2()
@onready var mousePosGlobal : Vector2 = Vector2()
@onready var mouseStartPos : Vector2 = Vector2()
@onready var mouseStartPosGlobal : Vector2 = Vector2()
@onready var mouseEndPos : Vector2 = Vector2()
@onready var mouseEndPosGlobal : Vector2 = Vector2()
@onready var target_box_size : Vector2 = Vector2()
@onready var target_box_position : Vector2 = Vector2()
@onready var is_dragging : bool = false

func _ready():
	pass

func _input(event):
	get_mouse_click_pos(event)

func _process(delta):
	get_choose_box_info()

func get_mouse_click_pos(event):
	if event is InputEventMouse:
		mousePos = event.position
		mousePosGlobal = get_global_mouse_position()
		mousePos = mousePosGlobal     # 此处如此编写仅为预留，别管

func get_box_size():
	target_box_size = Vector2()
	target_box_size = Vector2(abs(mouseEndPos.x - mouseStartPos.x), abs(mouseEndPos.y - mouseStartPos.y))

func get_box_position():
	target_box_position = Vector2()
	target_box_position = Vector2(min(mouseStartPos.x, mouseEndPos.x), min(mouseStartPos.y, mouseEndPos.y))
	
func get_choose_box_info():
	if Input.is_action_just_pressed("MouseLeftClick"):
		mouseStartPos = mousePos
		mouseStartPosGlobal = mousePosGlobal
		is_dragging = true

	if Input.is_action_just_released("MouseLeftClick"):
		if mouseStartPos.distance_to(mousePos) > drag_distance_min_limit:
			mouseEndPos = mousePos
			mouseEndPosGlobal = mousePosGlobal
		else:
			mouseEndPos = mouseStartPos
		is_dragging = false
		get_choose_box(is_dragging)
	
	if is_dragging:
		mouseEndPos = mousePos
		mouseEndPosGlobal = mousePosGlobal
		get_choose_box(is_dragging)

func get_choose_box(dragState = false):
	get_box_position()
	get_box_size()
	box.position = target_box_position
	box.size = target_box_size
	box.size *= int(dragState)

